﻿using BJ.AuthEntity.Models;
using Syspetro.Core.AppDeal;
using Syspetro.Core.CommandBus;
using Syspetro.Core.Resources;
using Syspetro.Core.SysInterface;
using Syspetro.Deploy.Managers;
using System;

namespace BJ.AuthDomain.Commands
{
    /// <summary>
    /// 发送手机验证码(需要登录)
    /// </summary>
    public class SendSMSCommandUser : Command
    {
        public Guid UserId { get; set; }
        public bool IsAdmin { get; set; }
    }
    public interface ISendSMSCommandUserHandler : ICommandHandler<SendSMSCommandUser>, ITransientService
    {

    }
    public class SendSMSCommandUserHandler : CommandHandler<SendSMSCommandUser>, ISendSMSCommandUserHandler
    {
        readonly IAuthorizationManager _authorization;
        readonly IFreeSql _freeSql;
        readonly ICommandBus _command;
        public SendSMSCommandUserHandler(IFreeSql freeSql, ICommandBus command, IAuthorizationManager authorization)
        {
            _freeSql = freeSql;
            _command = command;
            _authorization = authorization;
        }
        public override SpActionResult<string> Execute(SendSMSCommandUser command)
        {
            if (command.UserId == Guid.Empty)
            {
                command.UserId = _authorization.GetUserId;
                command.IsAdmin = _authorization.IsAdmin;
            }
            if(command.IsAdmin)
            {
                var user = _freeSql.Select<AdminUser>().Where(t => t.Id == command.UserId).First();
                if (user != null)
                {
                    return DoExecute(user.Phone);
                }
                else
                {
                    return new SpActionResult<string> { Msg = SharedResource.GetUserFailed, Success = false };
                }
            }
            else
            {
                var user = _freeSql.Select<User>().Where(t => t.Id == command.UserId).First();
                if (user != null)
                {
                    return DoExecute(user.Phone);
                }
                else
                {
                    return new SpActionResult<string> { Msg = SharedResource.GetUserFailed, Success = false };
                }
            }
        }
        public SpActionResult<string> DoExecute(string acc)
        {
            if (string.IsNullOrEmpty(acc))
                return new SpActionResult<string> { Success = false, Msg = SharedResource.NotSetPhone };
            var srsult = _command.Send(new SendSMSCommand { Phone = acc });
            return srsult.Get();
        }
    }
}
